﻿import {
    Component,
    Injector,
    ViewChild,
    ViewEncapsulation,
    OnInit,
    AfterViewInit,
} from "@angular/core";
import { ActivatedRoute } from "@angular/router";
import { AppConsts } from "@shared/AppConsts";
import { appModuleAnimation } from "@shared/animations/routerTransition";
import { AppComponentBase } from "@shared/common/app-component-base";
import {
    EntityDtoOfInt64,
    UserListDto,
    UserServiceProxy,
    OrderServiceProxy,
    OrderMainOutput,
} from "@shared/service-proxies/service-proxies";
import { FileDownloadService } from "@shared/utils/file-download.service";
import { LazyLoadEvent } from "primeng/components/common/lazyloadevent";
import { Paginator } from "primeng/components/paginator/paginator";
import { Table } from "primeng/components/table/table";
import { HttpClient } from "@angular/common/http";
import { FileUpload } from "primeng/fileupload";
import { finalize } from "rxjs/operators";
import * as moment from "moment";
import { CreateOrEditOrderModalComponent } from "./create-or-edit-order-modal.component";
import { QrScannerComponent } from "angular2-qrscanner";

@Component({
    templateUrl: "./main.component.html",
    encapsulation: ViewEncapsulation.None,
    styleUrls: ["./main.component.less"],
    animations: [appModuleAnimation()],
})
export class MainComponent extends AppComponentBase
    implements AfterViewInit, OnInit {
    @ViewChild("dataTable") dataTable: Table;
    @ViewChild("paginator") paginator: Paginator;

    @ViewChild("ExcelFileUpload") excelFileUpload: FileUpload;
    @ViewChild("createOrEditOrderModal")
    createOrEditOrderModal: CreateOrEditOrderModalComponent;

    @ViewChild("qrScannerComponent") qrScannerComponent: QrScannerComponent;
    // @ViewChild("laborCardModal") laborCardModal: LaborCardModalComponent;

    ngOnInit(): void {}
    ngAfterViewInit(): void {
        this.getOrders();
    }
    uploadUrl: string;
    public dateRange: Date[] = [
        moment().add(-3, "month").startOf("day").toDate(),
        moment().add(1, "day").endOf("day").toDate(),
    ];

    //Filters
    advancedFiltersAreShown = false;
    filterText = "";
    filterTaskNoText = "";
    filterPicNoText = "";
    filterNameText = "";
    filterCustomText = "";
    onlyUrgency = false;

    scannerEnabled = false;

    isScaning = false;

    constructor(
        injector: Injector,
        private _orderServiceProxy: OrderServiceProxy,
        private _fileDownloadService: FileDownloadService,
        private _activatedRoute: ActivatedRoute,
        private _httpClient: HttpClient
    ) {
        super(injector);
    }
    openscan(): void {
        this.isScaning = !this.isScaning;
        if (this.isScaning) {
            this.qrScannerComponent.getMediaDevices().then((devices) => {
                console.log(devices);
                const videoDevices: MediaDeviceInfo[] = [];
                for (const device of devices) {
                    if (device.kind.toString() === "videoinput") {
                        videoDevices.push(device);
                    }
                }
                if (videoDevices.length > 0) {
                    let choosenDev;
                    for (const dev of videoDevices) {
                        if (dev.label.includes("back")) {
                            choosenDev = dev;
                            break;
                        }
                    }
                    if (choosenDev) {
                        this.qrScannerComponent.chooseCamera.next(choosenDev);
                    } else {
                        this.qrScannerComponent.chooseCamera.next(
                            videoDevices[0]
                        );
                    }
                }
            });

            // this.qrScannerComponent.capturedQr.subscribe((result) => {
            //     //console.log(result);
            //     this.qrScannerComponent.stopScanning();
            //     this.isScaning = false;
            //     this.laborCardModal.show(result);
            // });
        } else {
            this.qrScannerComponent.stopScanning();
            this.isScaning = false;
        }
    }

    onCodeResult(resultString: string) {
        this.createOrEditOrderModal.show(1);
    }

    getOrders(event?: LazyLoadEvent) {
        if (this.primengTableHelper.shouldResetPaging(event)) {
            this.paginator.changePage(0);

            return;
        }

        this.primengTableHelper.showLoadingIndicator();

        this._orderServiceProxy
            .getOrders(
                moment(this.dateRange[0]).add(1, "day"),
                moment(this.dateRange[1]).add(1, "day"),
                this.filterPicNoText,
                this.filterTaskNoText,
                this.filterNameText,
                this.filterCustomText,
                this.onlyUrgency,
                this.primengTableHelper.getSorting(this.dataTable),
                this.primengTableHelper.getMaxResultCount(
                    this.paginator,
                    event
                ),
                this.primengTableHelper.getSkipCount(this.paginator, event)
            )

            .pipe(
                finalize(() => this.primengTableHelper.hideLoadingIndicator())
            )
            .subscribe((result) => {
                this.primengTableHelper.totalRecordsCount = result.totalCount;
                this.primengTableHelper.records = result.items;
                this.primengTableHelper.hideLoadingIndicator();
            });
    }

    deleteOrder(order: OrderMainOutput): void {
        this.message.confirm(
            "确认删除订单[" + order.id + "]" + order.taskNo + "吗？",
            this.l("AreYouSure"),
            (isConfirmed) => {
                if (isConfirmed) {
                    this._orderServiceProxy
                        .deleteOrder(order.id)
                        .subscribe(() => {
                            this.getOrders();
                            this.notify.success(this.l("SuccessfullyDeleted"));
                        });
                }
            }
        );
    }
}
